package club.adger.controller;

import club.adger.entity.Account;
import club.adger.entity.Person;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.validation.Valid;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: Adger
 * @Date: 2020/08/28/13:34
 */
@Controller
@RequestMapping("/validator")
public class ValidatorHandler {

    /**
     * 这个方法只是为了绑定模型
     * @param model
     * @return
     */
    @GetMapping("/login")
    public String login(Model model){
        model.addAttribute("account",new Account());
        return "login";
    }

    /**
     * @Validated 注解 代表验证器 验证
     * @param account
     * @param result
     * @return
     */
    @PostMapping("/login")
    public String login(@Validated Account account, BindingResult result){
        //是否有错
        if (result.hasErrors()){
            return "login";
        }
        return "index";
    }

    /**
     * 就是模仿数据库
     * @param model
     * @return
     */
    @GetMapping("/register2")
    public String register(Model model){
        model.addAttribute("person",new Person());
        return "register2";
    }

    @PostMapping("/register2")
    public String register(@Valid Person person, BindingResult result){
        //是否有错
        if (result.hasErrors()){
            return "register2";
        }
        return "index";
    }
}
